package com.panshi.controller;

import com.alibaba.fastjson.JSON;
import com.panshi.api.bean.ArticleBean;
import com.panshi.api.bean.ArticleNoBean;
import com.panshi.api.util.PageSizeVO;
import com.panshi.pojo.ArticleVO;
import com.panshi.pojo.TimeVO;
import com.panshi.pojo.UserCollectionVO;
import com.panshi.servers.ArticleService;
import com.panshi.servers.UserCollectionServers;
import com.rabbitmq.client.Channel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XiaoWangYa
 * @version 1.0
 * @date 2020/8/4 0004 下午 2:45
 */
@Slf4j
@Controller
@ApiModel("文章Controller层")
public class ArticleController {

    @Autowired  // 文章Servers层
    private ArticleService yb_articleService;

    @Autowired  // 文章收藏 Servers层
    private UserCollectionServers userCollectionServers;

    @PostMapping("/addArticle")
    @ResponseBody
    @ApiOperation("新增文章咨询")
    public String addArticleInfo (@RequestBody ArticleBean articleBean) {
        log.info("新增了文章内容 --> " + articleBean);
        // 类型转换
        ArticleVO article = new ArticleVO();
        BeanUtils.copyProperties(articleBean,article);

        // 获取文章中的图片路径
        String regex;
        List<String> srcList = new ArrayList<String>();
        regex = "src=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(article.getA_content());
        while (ma.find()){
//            srcList.add(ma.group());
            article.setImgpath(ma.group());
        }
        /* 多图片时使用
        String path = "";
        for (String s : srcList) {
            String[] split = s.split("=");
            for (int i = 0; i < split.length; i++) {
                if (i % 2 != 0) {
                    path += split[i]+",";
                }
            }
        }
        // 将图片路径存入实体类
        yb_Article_VO.setImgpath(path);*/
        // 存入数据库
        yb_articleService.addArticleInfo(article);
        return "ok";
    }

    @ApiOperation("新增站内消息数据")
    public String addInstation (@RequestBody ArticleBean articleBean) {
        log.info("新增站内消息数据 --> " + articleBean);
        // 类型转换
        ArticleVO Article = new ArticleVO();
        BeanUtils.copyProperties(articleBean,Article);
        // 获取文章中的图片路径
        String regex;
        List<String> srcList = new ArrayList<String>();
        regex = "src=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(Article.getA_content());
        while (ma.find()){
//            srcList.add(ma.group());
            Article.setImgpath(ma.group());
        }
        /* 多图片时使用
        String path = "";
        for (String s : srcList) {
            String[] split = s.split("=");
            for (int i = 0; i < split.length; i++) {
                if (i % 2 != 0) {
                    path += split[i]+",";
                }
            }
        }
        // 将图片路径存入实体类
        yb_Article_VO.setImgpath(path);*/
        // 存入数据库
        yb_articleService.addInstation(Article);
        return "ok";
    }

    @PostMapping("/deleteArticleInfo/{id}")
    @ResponseBody
    @ApiOperation("伪删除文章咨询")
    public String deleteArticleInfo (@PathVariable int id){
        log.info("伪删除了文章内容 --> " + id);
        yb_articleService.deleteArticleInfo(id);
        return "ok";
    }

    @PostMapping("/delArticleInfo/{id}")
    @ResponseBody
    @ApiOperation("删除文章咨询")
    public String delArticleInfo (@PathVariable int id){
        log.info("删除了文章内容 --> " + id);
        yb_articleService.delArticleInfo(id);
        return "ok";
    }

    @PostMapping("/queryArticleInfo")
    @ResponseBody
    @ApiOperation("查询所有文章咨询信息")
    public List<ArticleBean> queryArticleInfo (@RequestBody PageSizeVO pageSizeBean) {
        log.info("查询今日推荐文章内容 --> " + pageSizeBean);
        // 获取分页起始页
        pageSizeBean.setStartIndex(pageSizeBean.getStartIndexInfo());
        // 获取数据
        List<ArticleVO> articleVOS = yb_articleService.queryArticleInfo(pageSizeBean);
        // 类型转换
        List<ArticleBean> list = new ArrayList<>();
        for (ArticleVO articleVO : articleVOS) {
            ArticleBean article = new ArticleBean();
            // 数据转换
            BeanUtils.copyProperties(articleVO,article);
            // 将时间进行转换为xxx前发布
            String timeFormatText = TimeVO.getTimeFormatText(articleVO.getAudit_time());
            article.setDateTime(timeFormatText);
            list.add(article);
        }
        return list;
    }

    @PostMapping("/queryArticleVerifiedInfo")
    @ResponseBody
    @ApiModelProperty("查询文章审核通过信息")
    public PageSizeVO queryArticleVerifiedInfo (@RequestBody PageSizeVO yb_PageSize_VO) {
        log.info("查询文章审核通过信息 --> " + yb_PageSize_VO);
        // 获取分页起始页
        yb_PageSize_VO.setStartIndex(yb_PageSize_VO.getStartIndexInfo());
        List<ArticleVO> articleVOS = yb_articleService.adminQueryArticleInfo(yb_PageSize_VO);
        // 类型转换
        List<ArticleBean> list = new ArrayList<>();
        for (ArticleVO articleVO : articleVOS) {
            ArticleBean article = new ArticleBean();
            // 数据转换
            BeanUtils.copyProperties(articleVO,article);
            // 将时间进行转换为xxx前发布
            String timeFormatText = TimeVO.getTimeFormatText(articleVO.getAudit_time());
            article.setDateTime(timeFormatText);
            list.add(article);
        }
        // 返回类型
        PageSizeVO page = new PageSizeVO();
        page.setData(list); // 存入数据
        page.setCount(yb_articleService.queryArticleCount());   // 存入文章总数量
        return page;
    }

    @PostMapping("/queryHotArticleInfo")
    @ResponseBody
    @ApiModelProperty("查询热门文章咨询")
    public List<ArticleBean> queryHotArticleInfo (@RequestBody PageSizeVO yb_PageSize_VO) {
        log.info("查询热门文章内容 --> " + yb_PageSize_VO);
        // 获取分页起始页
        yb_PageSize_VO.setStartIndex(yb_PageSize_VO.getStartIndexInfo());
        // 获取热门文章咨询信息
        List<ArticleVO> articleVOS = yb_articleService.queryHotArticleInfo(yb_PageSize_VO);
        // 类型转换
        List<ArticleBean> list = new ArrayList<>();
        for (ArticleVO articleVO : articleVOS) {
            ArticleBean article = new ArticleBean();
            // 数据转换
            BeanUtils.copyProperties(articleVO,article);
            // 将时间进行转换为xxx前发布
            String timeFormatText = TimeVO.getTimeFormatText(articleVO.getAudit_time());
            article.setDateTime(timeFormatText);
            list.add(article);
        }
        return list;
    }

    @PostMapping("/queryNewArticleInfo")
    @ResponseBody
    @ApiModelProperty("查询最新文章内容")
    public List<ArticleBean> queryNewArticleInfo (@RequestBody PageSizeVO yb_PageSize_VO) {
        log.info("查询最新文章内容 --> " + yb_PageSize_VO);
        // 获取分页起始页
        yb_PageSize_VO.setStartIndex(yb_PageSize_VO.getStartIndexInfo());
        List<ArticleVO> articleVOS = yb_articleService.queryNewArticleInfo(yb_PageSize_VO);
        // 类型转换
        List<ArticleBean> list = new ArrayList<>();
        for (ArticleVO articleVO : articleVOS) {
            ArticleBean article = new ArticleBean();
            // 数据转换
            BeanUtils.copyProperties(articleVO,article);
            // 将时间进行转换为xxx前发布
            String timeFormatText = TimeVO.getTimeFormatText(articleVO.getAudit_time());
            article.setDateTime(timeFormatText);
            list.add(article);
        }
        return list;
    }

    @PostMapping("/queryAssignArticleInfo/{aid}")
    @ResponseBody
    @ApiModelProperty("查询指定文章内容")
    public ArticleVO queryAssignArticleInfo (@PathVariable int aid) {
        log.info("查询指定文章内容 --> " + aid);
        // 获取所查询的文章信息
        ArticleVO yb_article_vo = yb_articleService.queryAssignArticleInfo(aid);
        // 文章阅读量 +1
        yb_articleService.addReadCount(aid);
        // 搜索表 阅读量 +1
        yb_articleService.addSearchReadCount(aid);
        return yb_article_vo;
    }

    @PostMapping("/userArticleCollection")
    @ResponseBody
    @ApiModelProperty("文章收藏")
    public int addCollectSum (@RequestBody UserCollectionVO yb_UserCollection_VO) {
        log.info("增加文章收藏量 --> " + yb_UserCollection_VO);
        // 查询用户是否收藏指定文章
        UserCollectionVO userCollection = userCollectionServers.queryUserIFCollectionAtricle(yb_UserCollection_VO);
        if (userCollection != null) {
            /*if (yb_UserCollection_VO.getType_id().equals("2")) {
                // 收藏量 -1
                yb_article_vo.setCollect_count(yb_article_vo.getCollect_count() - 1);
                // 存入数据库
                yb_articleService.updateAssignArticleInfo(yb_article_vo);
                // 修改文章收藏数据
                userCollectionServers.userCancelArticleCollection(yb_UserCollection_VO);
                return yb_article_vo.getCollect_count();
            } else if (yb_UserCollection_VO.getType_id().equals("0")) {
                // 收藏量 +1
                yb_article_vo.setCollect_count(yb_article_vo.getCollect_count() + 1);
                // 存入数据库
                yb_articleService.updateAssignArticleInfo(yb_article_vo);
                // 修改文章收藏数据
                userCollectionServers.userCancelArticleCollection(yb_UserCollection_VO);
                return yb_article_vo.getCollect_count();
            } else {
                return yb_article_vo.getCollect_count();
            }*/
            // 查询指定文章内容
            ArticleVO yb_article_vo = yb_articleService.queryAssignArticleInfo(yb_UserCollection_VO.getAid());
            return yb_article_vo.getCollect_count();
        } else {
            // 查询指定文章内容
            ArticleVO yb_article_vo = yb_articleService.queryAssignArticleInfo(yb_UserCollection_VO.getAid());
            // 文章收藏量 +1
            yb_articleService.addCollectCount(yb_article_vo.getAid());
            // 搜索表收藏量 +1
            yb_articleService.addSearchCollectCount(yb_article_vo.getAid());
            // 增加文章收藏数据
            userCollectionServers.addUserCollectionInfo(yb_UserCollection_VO);
            return yb_article_vo.getCollect_count() + 1;
        }
    }

    @PostMapping("/randomQueryArticle")
    @ResponseBody
    @ApiModelProperty("随机查询(专家推荐、大家都在看、其他看点、相关推荐")
    public List<ArticleBean> randomQueryArticle(@RequestBody PageSizeVO yb_PageSize_VO) {
        log.info("随机查询 --> " + yb_PageSize_VO);
        // 设置分页初始页
        yb_PageSize_VO.setStartIndex(yb_PageSize_VO.getStartIndexInfo());
        // 获取数据
        List<ArticleVO> articleVOS = yb_articleService.randomQueryArticle(yb_PageSize_VO);
        // 类型转换
        List<ArticleBean> list = new ArrayList<>();
        for (ArticleVO articleVO : articleVOS) {
            ArticleBean article = new ArticleBean();
            // 数据转换
            BeanUtils.copyProperties(articleVO,article);
            // 将时间进行转换为xxx前发布
            String timeFormatText = TimeVO.getTimeFormatText(articleVO.getAudit_time());
            article.setDateTime(timeFormatText);
            list.add(article);
        }
        return list;
    }

    @PostMapping("/updateAssignArticleInfo")
    @ResponseBody
    @ApiModelProperty("修改指定文章内容")
    public String updateAssignArticleInfo (@RequestBody ArticleVO yb_Article_VO) throws Exception {
        log.info("修改指定文章内容");
        System.out.println(yb_Article_VO);
        if (yb_Article_VO.getState() != null && !yb_Article_VO.getState().equals("")) {  // 管理员修改
            // 获取数据
            ArticleVO articleVO = yb_articleService.queryAssignArticleInfo(yb_Article_VO.getAid());
            System.out.println("查询状态======================================");
            System.out.println(yb_Article_VO.getTid());
            if (yb_Article_VO.getTid() != 0) {
                // 管理员修改文章所属类型
                System.out.println(yb_Article_VO.getTid());
                System.out.println(articleVO);
                articleVO.setTid(yb_Article_VO.getTid());
            }
            // 管理员修改文章状态
            articleVO.setState(yb_Article_VO.getState());
            // 存入数据库
            yb_articleService.updateAssignArticleInfo(articleVO);
            return "ok";
        } else { // 用户自己修改
            // 获取文章中的图片路径
            String regex;
            List<String> srcList = new ArrayList<String>();
            regex = "src=\"(.*?)\"";
            Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
            Matcher ma = pa.matcher(yb_Article_VO.getA_content());
            while (ma.find()){
                yb_Article_VO.setImgpath(ma.group());
            }
            // 存入数据库
            yb_articleService.updateAssignArticleInfo(yb_Article_VO);
            return "ok";
        }
    }


    public static final  String EX_NAME="my-queue-article";

    //定义一个交换器名称绑定的消息队列名称1
    public static final String EX_NAME_MQ_NAME_1="my-article-mq-1";

    @RabbitListener(ackMode = "MANUAL",bindings = @QueueBinding(
            //声明队列     true代表持久的
            value = @Queue(value = EX_NAME_MQ_NAME_1/*, durable = "true"*/),
            exchange = @Exchange(
                    value = EX_NAME,//代表路由 EX_NAME_MQ_NAME_1->路由名称
                    type = ExchangeTypes.FANOUT //路由器的类型
            )))//
    public void myfountarticle(String articleNoBean,Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {

        System.out.println("我接收到了消息=================================================");
        ArticleNoBean articleNoBean1 = JSON.parseObject(articleNoBean, ArticleNoBean.class);
        System.out.println(articleNoBean1);
        channel.basicAck(tag,false);

    }


}
